using CMS.Entity;
using CMS.Service;
using CMS.Web.Attributes;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace CMS.Web.Controllers;

public class ImageController(
    IImageService imageService,
    IImageServerService imageServerService,
    IHttpClientFactory httpClientFactory) : Controller {
    // GET
    public IActionResult Index() {
        return View();
    }

    [HttpPost]
    [UnitOfWork]
    public async Task<IActionResult> ImageUpload(IFormFile? image) {
        if (image == null || image.Length == 0) {
            return BadRequest();
        }

        var imageServers = await imageServerService.Get(server => server.IsDeleted == false).ToListAsync();
        int count = imageServers.Count;
        int index = Random.Shared.Next(0, count);
        //构建请求
        var httpClient = httpClientFactory.CreateClient();
        // 构建 multipart/form-data 内容
        using var content = new MultipartFormDataContent();
        // 添加文件内容
        await using var stream = image.OpenReadStream();
        var fileContent = new StreamContent(stream);
        content.Add(fileContent, "image", image.FileName);
        var response = await httpClient.PostAsync(imageServers[index].ServerUrl + "/home/imageUpload", content);
        if (!response.IsSuccessStatusCode) {
            string respString = await response.Content.ReadAsStringAsync();
            throw new HttpRequestException($"上传失败，状态码：{response.StatusCode}，响应报文：{respString}");
        }

        Image imageInfo = new() {
            ImageServerId = imageServers[index].Id,
            ImageName = imageServers[index].ServerUrl + "/" + await response.Content.ReadAsStringAsync(), // 接收文件服务器返回的数据。
            CreatedDate = DateTime.Now,
            EditDate = DateTime.Now,
            IsDeleted = false
        };
        await imageService.AddAsync(imageInfo);
        return Ok();
    }

    public IActionResult ShowImages() {
        return View();
    }

    public async Task<IActionResult> GetImages() {
        return Json(new { code = 200, data = await imageService.Get(i => i.IsDeleted == false).ToListAsync() });
    }
}